import React, { Component } from 'react';
import {
	StyleSheet, Text, View, Platform, PixelRatio,
	ActivityIndicator, UIManager
} from "react-native";
import ScrollableTabView, { ScrollableTabBar } from 'react-native-scrollable-tab-view';
import { style } from '../../../theme/style';
import { GLOBAL } from '../../../config/global';
import { reportStyle } from './_common/style';
import chartOption from './_common/chartOption';
import Echarts from 'native-echarts';
import HTTP from '../../../utils/http';
import { API, API_GENERATE } from '../../../config/api';

const scale = GLOBAL.SCALE;
export class SalesReportSection extends Component {
	constructor(props) {
		super(props);
		let { data } = props;
		this.state = {
			loaded: false,
			stockData: null,
			priceData: null,
			choice: data && data.choice || { corpId: '' }
		}
		this.menuData = data && data.menuData || [];
		this._renderContent = this._renderContent.bind(this);
		this.refState = '库存成交情况'; // 初始化高度用
	}

	componentWillMount() {
		this.initialPage();
	}

	componentWillReceiveProps(props) {
		if (this.state.choice === props.data.choice) return
		this.setState({
			choice: props.data.choice || { corpId: '' }
		}, () => {
			this.initialPage();
		})
	}
	initialPage() {
		this.getStockData(); //库存成交
		this.getPriceData(); //成交均价
	}

	async getStockData() {
		const response = await HTTP.POST(API_GENERATE(API.GET_REPORT_SALES_STOCK), { bizDate: '', corpId: this.state.choice.corpId });
		this.setState({
			stockData: response
		})
	}

	async getPriceData() {
		const response = await HTTP.POST(API_GENERATE(API.GET_REPORT_SALES_PRICE), { bizDate: '', corpId: this.state.choice.corpId });
		this.setState({
			priceData: response
		})
	}


	setContentTitle(curMenu) {
		if (curMenu == 'stock') {
			return '库存成交情况'
		} else if (curMenu == 'price') {
			return '成交报告下单均价'
		}
	}

	setOption(curMenu) {
		chartOption.SET_OPTIONS.PRICE.yAxis.data = [];
		chartOption.SET_OPTIONS.PRICE.series[0].data = [];
		chartOption.SET_OPTIONS.PRICE.series[1].data = [];
		if (curMenu == 'stock') {
			const { stockData } = this.state;
			const { ownSalesStockTO, unifiedSalesStockTO } = stockData || {};
			chartOption.SET_OPTIONS.STOCK.series[0].data = [unifiedSalesStockTO.openStockQuantity, unifiedSalesStockTO.reportOpenStockQuantity, unifiedSalesStockTO.saleQuantity];
			chartOption.SET_OPTIONS.STOCK.series[1].data = [ownSalesStockTO.openStockQuantity, ownSalesStockTO.reportOpenStockQuantity, ownSalesStockTO.saleQuantity];

			return chartOption.SET_OPTIONS.STOCK
		} else if (curMenu == 'price') {
			const { priceData } = this.state;
			priceData && priceData.length && priceData.map((item, index) => {
				chartOption.SET_OPTIONS.PRICE.yAxis.data.push(item.bizLineName);
				chartOption.SET_OPTIONS.PRICE.series[0].data.push(item.unifiedSalesPrice);
				chartOption.SET_OPTIONS.PRICE.series[1].data.push(item.ownSalesPrice);
			})

			return chartOption.SET_OPTIONS.PRICE
		}
	}

	renderDateList(curMenu) {
		if (curMenu == 'stock') {
			const { stockData } = this.state;
			const { ownSalesStockTO, unifiedSalesStockTO, salesStockList } = stockData || {};
			return (
				<View style={[styles.panelViewDataList, { paddingBottom: 30 * scale }]}>
					<View style={styles.panelViewDataListLabel}>
						<Text style={styles.stockDataListLabel}>敞口库存</Text>
						<Text style={styles.stockDataListLabel}>上报敞口</Text>
						<Text style={styles.stockDataListLabel}>成交下单</Text>
					</View>
					<View style={styles.panelViewDataListItemView}>
						<View style={styles.panelViewDataListItemTipView}>
							<Text style={styles.panelViewDataListItemTip}>合计</Text>
						</View>
						<View style={styles.panelViewDataListItem}>
							<Text style={[styles.panelViewDataListItemLabel, { color: '#01B0F0' }]}>统销</Text>
							<Text style={[styles.panelViewDataListItemValue, { color: '#01B0F0' }]}>{unifiedSalesStockTO.openStockQuantity}</Text>
							<Text style={[styles.panelViewDataListItemValue, { color: '#01B0F0' }]}>{unifiedSalesStockTO.reportOpenStockQuantity}</Text>
							<Text style={[styles.panelViewDataListItemValue, { color: '#01B0F0' }]}>{unifiedSalesStockTO.saleQuantity}</Text>
						</View>
						<View style={styles.panelViewDataListItem}>
							<Text style={[styles.panelViewDataListItemLabel, { color: '#72AC4D' }]}>市场化</Text>
							<Text style={[styles.panelViewDataListItemValue, { color: '#72AC4D' }]}>{ownSalesStockTO.openStockQuantity}</Text>
							<Text style={[styles.panelViewDataListItemValue, { color: '#72AC4D' }]}>{ownSalesStockTO.reportOpenStockQuantity}</Text>
							<Text style={[styles.panelViewDataListItemValue, { color: '#72AC4D' }]}>{ownSalesStockTO.saleQuantity}</Text>
						</View>
					</View>
					{
						salesStockList && salesStockList.length > 0 ?
							salesStockList.map((item, index) => {
								return (
									<View key={index} style={styles.panelViewDataListItemView}>
										<View style={styles.panelViewDataListItemTipView}>
											<Text style={styles.panelViewDataListItemTip}>{item.bizLineName}</Text>
										</View>
										{
											item.salesStockList && item.salesStockList.length ?
												item.salesStockList.map((item, index) => {
													return (
														<View key={index} style={styles.panelViewDataListItem}>
															<Text style={[styles.panelViewDataListItemLabel]}>{item.isUnite ? '统销' : '市场化'}</Text>
															<Text style={[styles.panelViewDataListItemValue]}>{item.openStockQuantity}</Text>
															<Text style={[styles.panelViewDataListItemValue]}>{item.reportOpenStockQuantity}</Text>
															<Text style={[styles.panelViewDataListItemValue]}>{item.saleQuantity}</Text>
														</View>
													)
												}) : null
										}
									</View>
								)
							}) : null
					}
				</View>
			)
		} else if (curMenu == 'price') {
			const { priceData } = this.state;
			return (
				<View style={[styles.panelViewDataList, { paddingBottom: 30 * scale }]}>
					<View style={styles.priceViewDataList}>
						<View style={[styles.priceDataListLabelView]}>
							<Text style={[styles.priceDataListLabel, { color: '#01B0F0' }]}>统销业务</Text>
							<View style={[styles.priceDataListLabelBorder, { backgroundColor: '#01B0F0' }]}>
							</View>
						</View>
						<View style={[styles.priceDataListLabelView]}>
							<Text style={[styles.priceDataListLabel, { color: '#72AC4D' }]}>市场化业务</Text>
							<View style={[styles.priceDataListLabelBorder, { backgroundColor: '#72AC4D' }]}>
							</View>
						</View>
					</View>
					{
						priceData && priceData.length ?
							priceData.map((item, index) => {
								return (
									<View key={index} style={[styles.panelViewDataListItemView, { flexDirection: 'row', paddingRight: 18 * scale }]}>
										<View style={styles.panelViewDataListItemTipView}>
											<Text style={styles.panelViewDataListItemTip}>{item.bizLineName}</Text>
										</View>
										<View style={styles.priceDataListItem}>
											<Text style={[styles.panelViewDataListItemValue, { textAlign: 'right' }]}>{item.unifiedSalesPrice}</Text>
											<Text style={[styles.panelViewDataListItemValue, { textAlign: 'right' }]}>{item.ownSalesPrice}</Text>
										</View>
									</View>
								)
							}) : null
					}
				</View>
			);
		}
	}

	_renderContent(curMenu) {
		return (
			<View style={styles.panelViewContainer}>
				<View style={reportStyle.panelViewTitleView}>
					<Text style={reportStyle.panelViewTitle}>{this.setContentTitle(curMenu)}</Text>
				</View>
				<View style={styles.panelViewChartView}>
					<Echarts width={340 * scale} height={300 * scale} option={this.setOption(curMenu)} />
				</View>
				{this.renderDateList(curMenu)}

			</View>
		);
	}
	_handleTabHeight(obj) {
		//通过ref获得当前页面的高度计算方法
		this.refs[obj.ref.props.tabLabel].measure(this._setTabHeight.bind(this));
		this.refState = obj.ref.props.tabLabel;
	}

	_setTabHeight(ox, oy, width, height, px, py) {
		const { creditOverview, creditRankingList } = this.state;
		//高度不为零时进行高度计算
		if (height != 0) {
			//获取左右的高度
			this.setState((prevState, props) => ({
				height,
			}));
			//判断是否是第一次取高度
			if (!this.state.firstTabSwitch) {
				//动态更改view的高度
				this.setState((prevState, props) => ({
					tabViewStyle: { height: this.state.height + 40 },
				}));
			} else {
				this.setState({
					firstTabSwitch: false
				})
			}
		}
	}

	// android 使用
	_layout(e) {
		let fullHeight = Platform.OS === 'android' ? 80 : 40;
		return new Promise((resolve) => {
			UIManager.measure(e.target, (x, y, width, height, pageX, pageY) => {
				this.setState((prevState, props) => ({
					tabViewStyle: { height: (height + fullHeight) * scale },
				}));
				resolve({
					x,
					y,
					width,
					height,
					pageX,
					pageY
				});
			});
		});
	}
	render() {
		const { loaded, stockData, priceData } = this.state;
		loadedCell = loaded ?
			<View style={styles.loadedCell}>
				<ActivityIndicator
					animating={true}
					color={'#fff'}
					size="small"
				/>
			</View> : null;
		const scrollableTabView = this.menuData.map(item => {
			const { key, text } = item;
			return (
				<View tabLabel={text} key={key} ref={text}>
					<View style={styles.panelCellView}>
						{stockData && priceData ? this._renderContent(key) : null}
					</View>
				</View>
			);
		});
		return (
			<View style={{ flex: 1, backgroundColor: '#EDF1FA' }}>
				<ScrollableTabView
					initialPage={0}
					locked={this.state.loaded}
					onChangeTab={(obj) => { this._handleTabHeight(obj) }}
					style={this.state.tabViewStyle}
					renderTabBar={() =>
						<ScrollableTabBar
							style={{
								borderBottomWidth: 0.5
							}}
							tabStyle={{ width: 130 }}
							underlineStyle={styles.tabBarUnderline}
							tabsContainerStyle={{ justifyContent: 'flex-start' }}
						/>
					}
					tabBarActiveTextColor='#031B31'
					tabBarTextStyle={{ color: '#031B31' }}
				>
					{scrollableTabView}
				</ScrollableTabView>
				{
					Platform.OS === 'android' && stockData && priceData ? <View style={styles.adAtive} onLayout={({ nativeEvent: e }) => this._layout(e)}>
						{this._renderContent(this.refState === "库存成交情况" ? 'stock' : 'price')}
					</View> : null
				}

			</View >
		);
	}
}

const styles = StyleSheet.create({
	panelCellView: {
		width: '94%',
		marginLeft: '3%',
		alignItems: 'center',
		marginTop: 20 * scale,
		marginBottom: 24 * scale,
		backgroundColor: '#fff',
		borderRadius: 10 * scale,
	},
	tabBarUnderline: {
		height: 0,
		width: 0,
		overflow: 'hidden',
		borderColor: '#EDF1FA',
		borderBottomColor: '#000',
		borderWidth: 10,
		borderLeftWidth: 5,
		borderRightWidth: 5,
		backgroundColor: 'transparent',
		marginLeft: 60
	},
	panelViewContainer: {
		width: '100%',
	},
	panelViewChartView: {
		height: 350 * scale,
		width: 360 * scale,
		padding: 14 * scale,
		overflow: "hidden"
	},
	panelViewDataListLabel: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'flex-end',
		marginLeft: 88 * scale
	},
	stockDataListLabel: {
		flex: 1,
		color: 'rgba(3,27,49,0.5)',
		fontSize: 12 * scale,
		padding: 10 * scale
	},
	panelViewDataListItemView: {
		borderTopColor: '#D0D1D2',
		borderTopWidth: 1 / PixelRatio.get(),
		paddingTop: 14 * scale,
		paddingBottom: 14 * scale,
	},
	panelViewDataListItemTipView: {
		width: 88 * scale,
		backgroundColor: 'rgba(1,176,240,.6)',
		paddingTop: 6 * scale,
		paddingBottom: 6 * scale,
		paddingLeft: 14 * scale,
		borderBottomEndRadius: 8 * scale,
		borderTopRightRadius: 8 * scale,
	},
	panelViewDataListItemTip: {
		color: '#fff',
		fontSize: 12 * scale,
	},
	panelViewDataListItem: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'flex-start',
		paddingLeft: 14 * scale,
		paddingTop: 18 * scale,
	},
	panelViewDataListItemLabel: {
		flex: 1,
		fontSize: 12 * scale,
		color: 'rgba(3,27,49,0.7)',
	},
	panelViewDataListItemValue: {
		flex: 1,
		textAlign: 'center',
		fontSize: 13 * scale,
		color: 'rgba(3,27,49,1)',
		fontWeight: '400'
	},
	priceDataListLabel: {
		textAlign: 'center',
		fontSize: 12 * scale,
		marginBottom: 10 * scale
	},
	priceDataListItem: {
		flex: 1,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'flex-end',
	},
	priceViewDataList: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'flex-end',
		marginLeft: 88 * scale,
		marginRight: 18 * scale
	},
	priceDataListLabelView: {
		flex: 1,
		flexDirection: 'column',
		alignItems: 'flex-end',
	},
	priceDataListLabelBorder: {
		width: '40%',
		height: 3 * scale
	},
	adAtive: {
		position: 'absolute',
		zIndex: -1,
		bottom: 0,
		left: 0,
		opacity: 0
	}
})